package com.jlect.swebing.renderers.gwt.client;

import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;
import com.jlect.swebing.renderers.client.PopupListener;
import com.jlect.swebing.renderers.client.PopupPanelRenderer;

/**
 * Container renderer GWT based implementation
 * @author Sergey Kozmin
 * @since 11.11.2007 21:02:27
 */
public class PopupContainerRendererGWTImpl extends ContainerRendererGWTImpl implements PopupPanelRenderer {
    protected Panel getPanel() {
        return (Panel) getPopup().getWidget();
    }

    protected LightPopup getPopup() {
        return (LightPopup) getWidget();
    }

    protected Widget provideWidget() {
        AbsolutePanel panel = new AbsolutePanel();
        panel.add(new Label("here it is"));
        return new LightPopupAttachSource(panel);
    }

    public void setVisible(boolean isVisible) {
        if(isVisible) {
            getPopup().show();
        } else {
            getPopup().hide();
        }
    }

    public boolean isVisible() {
        return getPopup().isShowing();
    }

    public void setLocation(int x, int y) {
        getPopup().setPopupPosition(x, y);
    }

    public int getX() {
        return getPopup().getPopupLeft();
    }

    public int getY() {
        return getPopup().getPopupTop();
    }

    public void setPopupListener(PopupListener listener) {
        getPopup().removeAllPopupListeners();
        if(listener != null) {
            getPopup().addPopupListener(listener);
        }
    }

    private static class LightPopupAttachSource extends LightPopup implements AttachEventSource {
        private AttachListener listener;

        public LightPopupAttachSource(Widget widget) {
            setWidget(widget);
        }

        public void setAttachListener(AttachListener listener) {
            this.listener = listener;
        }

        protected void onLoad() {
            super.onLoad();
            if(listener != null) {
                listener.onLoad();
            }
        }

        protected void onUnload() {
            super.onUnload();
            if(listener != null) {
                listener.onUnload();
            }
        }
    }
}